package com.dayuanit.dy17.atm.service.impl;

import com.dayuanit.dy17.atm.domain.FlowDomain;
import com.dayuanit.dy17.atm.dto.FlowDTO;
import com.dayuanit.dy17.atm.exception.BizException;
import com.dayuanit.dy17.atm.mapper.FlowMapper;
import com.dayuanit.dy17.atm.service.IFlowService;
import com.dayuanit.dy17.atm.util.DateUtils;
import com.dayuanit.dy17.atm.util.MoenyUtils;
import com.dayuanit.dy17.atm.util.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FlowServiceImpl implements IFlowService {

    @Autowired
    private FlowMapper flowMapper;

    @Override
    public PageHelper<List<FlowDTO>> loadFlows(long cardId, String password, int currentPage) {
        if (StringUtils.isBlank(password)) {
            throw new BizException("请输入密码");
        }

        int totalCount = flowMapper.countFlowByCardId(cardId);
        PageHelper<List<FlowDTO>> pageHelper = PageHelper.init(totalCount, currentPage, 3);

        List<FlowDomain> flowDomains = flowMapper.listFlowByCardId(cardId, pageHelper.offset(), 3);
        List<FlowDTO> dtos = new ArrayList<>(flowDomains.size());

        for (FlowDomain domain : flowDomains) {
            FlowDTO flowDTO = new FlowDTO();
            dtos.add(flowDTO);

            flowDTO.setAmount(MoenyUtils.fen2Yuan(domain.getAmount()));
            flowDTO.setCardNum(domain.getCardNum());
            flowDTO.setCreateTime(DateUtils.date2String(domain.getCreateTime()));
            flowDTO.setRemark(domain.getRemark());
        }

        pageHelper.setPageData(dtos);

        return pageHelper;
    }
}
